package cn.iocoder.yudao.module.system.job;

import cn.iocoder.yudao.framework.quartz.core.handler.JobHandler;
import cn.iocoder.yudao.framework.tenant.core.job.TenantJob;
import cn.iocoder.yudao.module.system.service.useractivity.UserActivityStatsService;
import cn.iocoder.yudao.module.system.service.userbehavior.UserBehaviorStatsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;

/**
 * 用户统计数据清理定时任务
 *
 * @author 系统开发团队
 */
@Component
@Slf4j
public class UserStatsCleanupJob implements JobHandler {

    @Resource
    private UserActivityStatsService userActivityStatsService;

    @Resource
    private UserBehaviorStatsService userBehaviorStatsService;

    @Override
    @TenantJob
    public String execute(String param) throws Exception {
        log.info("[execute] 开始执行用户统计数据清理定时任务");

        try {
            // 默认保留365天的统计数据，清理更早的数据
            int retentionDays = 365;
            if (param != null && !param.trim().isEmpty()) {
                try {
                    retentionDays = Integer.parseInt(param.trim());
                } catch (NumberFormatException e) {
                    log.warn("[execute] 参数解析失败，使用默认保留天数：{}", retentionDays);
                }
            }

            LocalDate cutoffDate = LocalDate.now().minusDays(retentionDays);
            LocalDateTime cutoffDateTime = cutoffDate.atStartOfDay();

            // 清理过期的活动统计数据
            int deletedActivityStats = userActivityStatsService.deleteExpiredStats(cutoffDate);
            log.info("[execute] 清理过期活动统计数据：{} 条，截止日期：{}", deletedActivityStats, cutoffDate);

            // 清理过期的日活动数据
            int deletedDailyActivity = userActivityStatsService.deleteExpiredDailyActivity(cutoffDate);
            log.info("[execute] 清理过期日活动数据：{} 条，截止日期：{}", deletedDailyActivity, cutoffDate);

            // 清理过期的行为统计数据
            int deletedBehaviorStats = userBehaviorStatsService.deleteExpiredBehaviorStats(cutoffDate);
            log.info("[execute] 清理过期行为统计数据：{} 条，截止日期：{}", deletedBehaviorStats, cutoffDate);

            // 清理过期的行为详情数据（保留30天）
            LocalDateTime behaviorDetailCutoff = LocalDate.now().minusDays(30).atStartOfDay();
            int deletedBehaviorDetails = userBehaviorStatsService.deleteExpiredBehaviorDetails(behaviorDetailCutoff);
            log.info("[execute] 清理过期行为详情数据：{} 条，截止时间：{}", deletedBehaviorDetails, behaviorDetailCutoff);

            // 清理过期的功能路径数据（保留90天）
            LocalDateTime featurePathCutoff = LocalDate.now().minusDays(90).atStartOfDay();
            int deletedFeaturePaths = userBehaviorStatsService.deleteExpiredFeaturePaths(featurePathCutoff);
            log.info("[execute] 清理过期功能路径数据：{} 条，截止时间：{}", deletedFeaturePaths, featurePathCutoff);

            // 返回执行结果
            String result = String.format("活动统计：%d条，日活动：%d条，行为统计：%d条，行为详情：%d条，功能路径：%d条",
                    deletedActivityStats, deletedDailyActivity, deletedBehaviorStats, 
                    deletedBehaviorDetails, deletedFeaturePaths);

            log.info("[execute] 完成执行用户统计数据清理定时任务，清理结果：{}", result);
            return result;

        } catch (Exception e) {
            log.error("[execute] 执行用户统计数据清理定时任务失败", e);
            throw e;
        }
    }
}